package upload

import (
	"fmt"
	"mime/multipart"
	"strings"
	"time"

	"uploadSvc/global"
	"uploadSvc/model/common/request"
	"uploadSvc/model/upload"
	uploadUtil "uploadSvc/utils/upload"
)

//@function: Upload
//@description: 创建文件上传记录
//@param: file model.FileUploadAndDownload
//@return: error

func (e *FileUploadAndDownloadService) Upload(file upload.FileUploadAndDownload) error {
	tx := global.NS_DB.Exec("INSERT INTO NANSHAN_DB.KPR_AUDIOS (PUBTIME, DEVICE_NUMBER, FILE_NAME, FILE_PATH, CREATED_AT) VALUES (?,?,?,?,?)", file.Pubtime, file.DeviceNumber, file.FileName, file.FilePath, file.CreatedAt)
	if tx.Error != nil {
		return tx.Error
	}
	return nil
}

//@function: FindFile
//@description: 查询文件记录
//@param: id uint
//@return: model.FileUploadAndDownload, error

func (e *FileUploadAndDownloadService) FindFile(id uint) (upload.FileUploadAndDownload, error) {
	var file upload.FileUploadAndDownload
	err := global.NS_DB.Where("id = ?", id).First(&file).Error
	return file, err
}

// EditFileName 编辑文件名或者备注
func (e *FileUploadAndDownloadService) EditFileName(file upload.FileUploadAndDownload) (err error) {
	var fileFromDb upload.FileUploadAndDownload
	return global.NS_DB.Where("id = ?", file.ID).First(&fileFromDb).Update("file_name", file.FileName).Error
}

//@function: GetFileRecordInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: list interface{}, total int64, err error

func (e *FileUploadAndDownloadService) GetFileRecordInfoList(info request.PageInfo) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	keyword := info.Keyword
	db := global.NS_DB.Model(&upload.FileUploadAndDownload{})
	var fileLists []upload.FileUploadAndDownload
	if len(keyword) > 0 {
		db = db.Where("file_name LIKE ?", "%"+keyword+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&fileLists).Error
	return fileLists, total, err
}

//@function: UploadFile
//@description: 根据配置文件判断是文件上传到本地或者七牛云
//@param: header *multipart.FileHeader, device_number string
//@return: file model.FileUploadAndDownload, err error

func (e *FileUploadAndDownloadService) UploadFile(header *multipart.FileHeader, device_number string, noSave string) (file upload.FileUploadAndDownload, err error) {
	oss := uploadUtil.NewOss()
	filePath, fileName, uploadErr := oss.UploadFile(header, device_number)
	if uploadErr != nil {
		panic(uploadErr)
	}
	f := upload.FileUploadAndDownload{
		FilePath:     filePath,
		FileName:     fileName,
		DeviceNumber: device_number,
		Pubtime:      formatPubTime(fileName),
		CreatedAt:    time.Now(),
	}
	if noSave == "0" {
		return f, e.Upload(f)
	}
	return f, nil
}

// 时间格式：noise_2024-09-12_12_08_56 要求返回"2024-09-12 12:08:56"
func formatPubTime(fileName string) time.Time {
	layout := "2006-01-02 15:04:05" // 对应的布局字符串
	fmt.Println("当前的fileName:", fileName)
	if strings.HasPrefix(fileName, "noise") {
		parts := strings.Split(fileName, "_")
		dateTimeStr := parts[1] + " " + parts[2] + ":" + parts[3] + ":" + parts[4]
		parsedTime, err := time.Parse(layout, dateTimeStr)
		if err != nil {
			return time.Now()
		}
		return parsedTime
	} else {
		return time.Now()
	}
}
